package com.hl.card.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public final class CommonUtil
{
  public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
  public static final String DATE_FORMAT = "yyyy-MM-dd";

  public static boolean isEmpty(List list)
  {
    return (list == null) || (list.size() == 0);
  }

  public static boolean isEmpty(Map map)
  {
    return (map == null) || (map.size() == 0);
  }

  public static boolean isEmpty(Set set)
  {
    return (set == null) || (set.size() == 0);
  }

  public static boolean isEmpty(String value)
  {
    return (value == null) || ("".equals(value.trim()));
  }

  public static boolean isEmpty(Object value)
  {
    return value == null;
  }

  public static boolean isEmpty(Long value)
  {
    return value == null;
  }

  public static boolean isEmpty(Integer value)
  {
    return value == null;
  }

  public static boolean isEmpty(String[] arrValue)
  {
    return (arrValue == null) || (arrValue.length == 0);
  }

  public static boolean isEmpty(Object[] arrObject)
  {
    return (arrObject == null) || (arrObject.length == 0);
  }

  public static boolean isNotEmpty(List list)
  {
    return !isEmpty(list);
  }

  public static boolean isNotEmpty(Map map)
  {
    return !isEmpty(map);
  }

  public static boolean isNotEmpty(Set set)
  {
    return !isEmpty(set);
  }

  public static boolean isNotEmpty(String value)
  {
    return !isEmpty(value);
  }

  public static boolean isNotEmpty(Object value)
  {
    return !isEmpty(value);
  }

  public static boolean isNotEmpty(Long value)
  {
    return !isEmpty(value);
  }
  public static boolean isNotEmpty(char value)
  {
	  String str=String.valueOf(value);
	  if(str.equals("")){
		  System.out.println(true);
		  return !isEmpty(value);
		  }
	  return isEmpty(value);
  }

  public static boolean isNotEmpty(Integer value)
  {
    return !isEmpty(value);
  }

  public static boolean isNotEmpty(String[] arrValue)
  {
    return !isEmpty(arrValue);
  }

  public static boolean isNotEmpty(Object[] arrObject)
  {
    return !isEmpty(arrObject);
  }

  public static boolean isNotZero(Integer aNum)
  {
    return (null != aNum) && (0 != aNum.intValue());
  }

  public static String getStringValue(Object value)
  {
    if (isEmpty(value)) {
      return "";
    }
    return value.toString();
  }

  public static boolean isDate(Calendar sysDate, Date dbDate)
  {
    SimpleDateFormat frm = new SimpleDateFormat("yyyy-MM-dd");
    String dbdateStr = frm.format(dbDate);
    String sysdateStr = frm.format(sysDate.getTime());

    return sysdateStr.equals(dbdateStr);
  }

  public static boolean lessSysDateTime(Calendar sysDate, Date dbDate)
  {
    return sysDate.getTime().getTime() > dbDate.getTime();
  }

  public static String formatDateString(String pattern, int field, int timeLapse)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.add(field, timeLapse);
    SimpleDateFormat frm = new SimpleDateFormat(pattern);
    String dateStr = frm.format(calendar.getTime());
    return dateStr;
  }

  public static String dateString(String pattern, Date date)
  {
    SimpleDateFormat frm = new SimpleDateFormat(pattern);
    String dateStr = frm.format(Long.valueOf(date.getTime()));
    return dateStr;
  }

  public static String getMD5Str(String str)
  {
    MessageDigest messageDigest = null;
    try
    {
      messageDigest = MessageDigest.getInstance("MD5");

      messageDigest.reset();

      messageDigest.update(str.getBytes("UTF-8"));
    }
    catch (NoSuchAlgorithmException e)
    {
      return "";
    }
    catch (UnsupportedEncodingException e)
    {
      return "";
    }

    byte[] byteArray = messageDigest.digest();

    StringBuffer md5StrBuff = new StringBuffer();

    for (int i = 0; i < byteArray.length; i++)
    {
      if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
        md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
      else {
        md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
      }
    }
    return md5StrBuff.toString();
  }

  public static boolean pageParmsIsEmpty(String allData, String page)
  {
    return (isEmpty(allData)) && (isEmpty(page));
  }

  public static boolean isInt(String str)
  {
    try
    {
      new Integer(str);

      return true;
    }
    catch (Exception e) {
    }
    return false;
  }

  public static boolean isLong(String str)
  {
    try
    {
      new Long(str);

      return true;
    }
    catch (Exception e) {
    }
    return false;
  }

  public static String datetostring24(Long date)
  {
    return dateString("yyyy-MM-dd HH:mm:ss", new Date(date.longValue()));
  }

  public static String enStringToZhString(String paramString)
  {
    return paramString.replaceAll("\"", "”");
  }

  public static String getCurrURLEncoder(String resourceName)
  {
    try
    {
      if (resourceName.length() > 6) {
        resourceName = resourceName.substring(6) + "...";
      }
      resourceName = URLEncoder.encode(resourceName, "UTF-8");
      resourceName = resourceName.replace("%", "-");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return resourceName;
  }

  public static boolean isDouble(String str)
  {
    if ((str != null) && (!str.trim().equals("")))
    {
        return str.matches("^[0-9]+[.]?[0-9]*$");
    }

    return false;
  }

  public static boolean isInt2(String str)
  {
    if (str != null)
    {
        return str.matches("\\d+");
    }
    return false;
  }

  public static String getOrderBackurl(String url, String orderResult, String userId)
  {
    userId = userId == null ? "" : userId;
    String parmStr = "orderResult=" + orderResult + "&userId=" + userId;
    if (url != null) {
      if (url.indexOf(".action?") <= 0)
        url = url + "?" + parmStr;
      else {
        url = url + "&" + parmStr;
      }
    }
    return url;
  }

  public static Date getTodayBefore(int intervalDays, String dateFormat)
  {
    Calendar calendar = Calendar.getInstance();

    calendar.add(5, -intervalDays);
    if ("Date".equals(dateFormat)) {
      calendar.set(11, 0);
      calendar.set(12, 0);
      calendar.set(13, 0);
      calendar.set(14, 0);
    }
    Date date = calendar.getTime();

    return date;
  }

  public static Date getToday2Before(int intervalDays)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.add(5, -intervalDays);
    Date date = calendar.getTime();
    return date;
  }

  public static String getTodayBefore(int intervalDays)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.add(5, -intervalDays);
    Date date = calendar.getTime();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String dayBefore = format.format(date);
    return dayBefore;
  }

  public static Date getTodayDateBefore(int intervalDays, String dateFormat)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.add(5, -intervalDays);
    Date date = calendar.getTime();
    return date;
  }

  public static Date getMinuteBefore(Date date, int intervalMinute)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(12, -intervalMinute);
    Date result = calendar.getTime();
    return result;
  }

  public static String getTodayAfter(int intervalDays)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.add(5, intervalDays);
    Date date = calendar.getTime();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String dayAfter = format.format(date);
    return dayAfter;
  }

  public static Date getToday2After(int intervalDays)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.add(5, intervalDays);
    Date date = calendar.getTime();
    return date;
  }

  public static Date getTodayBeforeHour(int afterHuor) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(10, -afterHuor);
    Date date = calendar.getTime();

    return date;
  }

  public static Date getDateTime(Date dateTime, int field, int amount)
  {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dateTime);
    calendar.add(field, amount);
    Date date = calendar.getTime();

    return date;
  }

  public static int getColLen(Collection list)
  {
    return list == null ? 0 : list.size();
  }

  public static boolean isHD(String[] type)
  {
    if (isEmpty(type)) {
      return false;
    }
    for (String str : type) {
      if ((str.equals("MPEG-2-HD")) || (str.equals("H.264-HD")))
      {
        return true;
      }
    }
    return false;
  }

  public static boolean isHD(String vedioType) {
    if (isEmpty(vedioType)) {
      return false;
    }
    return vedioType.equals("1");
  }

  public static String isHDStr(String[] type)
  {
    for (String str : type) {
      if ((str.equals("MPEG-2-HD")) || (str.equals("H.264-HD")))
      {
        return "1";
      }
    }
    return "0";
  }

  public static String transformConfigToVideoType(String ConfigStr)
  {
    if (ConfigStr.equals("1"))
      return "MPEG-2-HD";
    if (ConfigStr.equals("2"))
      return "MPEG-2-SD";
    if (ConfigStr.equals("3"))
      return "H.264-HD";
    if (ConfigStr.equals("4")) {
      return "H.264-SD";
    }
    return "MPEG-2-HD";
  }

  public static boolean isNumber(String s)
  {
    if (isEmpty(s))
      return false;
    try
    {
      Integer.parseInt(s);
    } catch (Exception e) {
      return false;
    }
    return true;
  }

  public static String getNameRemoveDigital(String name)
  {
    String result = name;
    int index = 0;
    for (int i = 0; i < name.length(); i++)
    {
      char ch = name.charAt(i);
      if ((ch < '0') || (ch > '9'))
        continue;
      index = i;
      break;
    }

    if (index == 0)
    {
      return result;
    }
    result = name.substring(0, index);

    return result;
  }

  public static String filtrateLetters(String userCode)
  {
    StringBuffer result = new StringBuffer(userCode);
    int count = 0;
    for (int i = 0; i < userCode.length(); i++)
    {
      char ch = userCode.charAt(i);
      if (((ch < 'a') || (ch > 'z')) && ((ch < 'A') || (ch > 'Z')))
        continue;
      result.deleteCharAt(i - count);
      count++;
    }

    return result.toString();
  }

  public static int time2Second(String runtime)
  {
    int timeCount = 0;
    try {
      String[] celltime = runtime.split(":");
      int hour = Integer.parseInt(celltime[0]);
      int minute = Integer.parseInt(celltime[1]);
      int second = Integer.parseInt(celltime[2]);
      timeCount = 3600 * hour + 60 * minute + second;
    } catch (Exception e) {
      int temptime = 0;
      try {
        temptime = Integer.parseInt(runtime);
      }
      catch (Exception e2) {
        return 0;
      }
      return temptime;
    }
    return timeCount;
  }

  public static String Filtername(String resourceName, String suffix, int beginIndex, int endIndex)
  {
    if (isEmpty(resourceName)) {
      resourceName = "";
    }
    if (isEmpty(suffix)) {
      suffix = "";
    }
    String name = resourceName;
    if (resourceName.length() > endIndex) {
      StringBuffer sb = new StringBuffer();
      sb.append(resourceName, beginIndex, endIndex);
      sb.append(suffix);
      name = sb.toString();
    }
    return name;
  }

  public static byte[] getBytesByList(List list)
  {
    byte[] bytes = null;
    try {
      ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
      ObjectOutputStream objectOut = new ObjectOutputStream(byteOut);
      objectOut.writeObject(list);
      bytes = byteOut.toByteArray();
    }
    catch (Exception e) {
      return null;
    }
    return bytes;
  }

  public static List getListBybytes(byte[] bytes)
  {
    List list = null;
    try {
      ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
      ObjectInputStream objectInputStream = new ObjectInputStream(byteIn);
      list = (List)objectInputStream.readObject();
    }
    catch (Exception e) {
      return null;
    }
    return list;
  }
  
  /**
   * 
   * @param ids
   * @return
   */
  public static String ArrayToStr(String[] ids){
	  if(ids == null || ids.length == 0){
		  return null;
	  }
	  StringBuilder sb = new StringBuilder();
	  for(int i =0 ;i< ids.length ; i++){
		  sb.append(ids[i]);
		  if((i+1) < ids.length){
			  sb.append(",");
		  }
	  }
	  return sb.toString();
  }
  
  public static String ArrayToStr1(String[] ids){
	  if(ids == null || ids.length == 0){
		  return null;
	  }
	  StringBuilder sb = new StringBuilder();
	  for(int i =0 ;i< ids.length ; i++){
		  sb.append("'").append(ids[i]).append("'");
		  if((i+1) < ids.length){
			  sb.append(",");
		  }
	  }
	  return sb.toString();
  }
  
  /**
   * 判断String数组中是否存在某值
   * @param arr
   * @param targetValue
   * @return
   */
  	public static boolean useLoop(String[] arr, String targetValue) {
	    for (String s : arr) {
	        if (s.equals(targetValue)) {
	            return true;
	        }
	    }
	    return false;
	}
  	/**
  	 * 验证姓名是否合格
  	 * @param userName
  	 * @return
  	 */
  	public static boolean validateUserName(String userName) {
		String validateStr = "^[\\w\\-－＿[0-9]\u4e00-\u9fa5\uFF21-\uFF3A\uFF41-\uFF5A]+$";
		boolean rs = false;
		rs = matcher(validateStr, userName);
		if (rs) {
			int strLenth = getStrLength(userName);
			if (strLenth <2 || strLenth > 15) {
				rs = false;
			}
		}
		return rs;
	}
  	
  	/**
  	 * 验证身份证
  	 * @param userName
  	 * @return
  	 */
	public static boolean validateIdNo(String idNo) {
		String validateStr1 = "^[a-zA-Z]{5,17}$";
		String validateStr2 = "^[a-zA-Z0-9]{5,17}$";
		boolean rs = false;
		boolean rs2 = false;
		rs = matcher(validateStr1, idNo);
		rs2 = matcher(validateStr2, idNo);
        return rs || rs2;
	}
  	
  	/**
	 * 获取字符串的长度，对双字符（包括汉字）按两位计数
	 * 
	 * @param value
	 * @return
	 */
	public static int getStrLength(String value) {
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		for (int i = 0; i < value.length(); i++) {
			String temp = value.substring(i, i + 1);
			if (temp.matches(chinese)) {
				valueLength += 2;
			} else {
				valueLength += 1;
			}
		}
		return valueLength;
	}

	private static boolean matcher(String reg, String string) {
		boolean tem = false;
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(string);
		tem = matcher.matches();
		return tem;
	}
  	/**
     * 判断int数组中是否存在某值
     * @param arr
     * @param targetValue
     * @return
     */
	public static boolean useLoopInt(int[] arr, int targetValue) {
	    for (int s : arr) {
	        if (s==targetValue) {
	            return true;
	        }
	    }
	    return false;
  	}
	
	/**
	 * 根据表名称 和 实体属性 创建一张表
	 * 
	 * @param tableName
	 * @param obj 具体生成什么样的表看该对象
	 */
	@SuppressWarnings("unchecked")
	public static String createTable(String tableName,Object obj, Map noCol) {
		StringBuffer sb = new StringBuffer();
		sb.append("CREATE TABLE `" + tableName + "` (");
		sb.append(" `id` int(11) NOT NULL AUTO_INCREMENT,");
		Class c = obj.getClass();
		Field[] field = c.getDeclaredFields();
		for (Field f : field) {
//			if (noCol.get(f.getName()) == null) {
				String type = f.getType().toString();
				if (type.equals("class java.lang.String")) {// Str
					sb.append("`" + f.getName()
							+ "` varchar(100) DEFAULT NULL,");
				} else if (type.equals("int")
						|| type.equals("class java.lang.Integer")) {// int
					sb.append("`" + f.getName() + "` int(11) DEFAULT NULL,");
				} else if (type.equals("double")
						|| type.equals("class java.lang.Double")) {// double
					sb.append("`" + f.getName() + "` double DEFAULT NULL,");
				}
//			}
		}
		sb.append(" `tableName` varchar(255) DEFAULT NULL,");
		sb.append(" PRIMARY KEY (`id`)");
		sb.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
		return sb.toString();
	}
	
	/**
	 * 获取小数点
	 * 
	 * @param value1
	 *            除数值
	 * @param value2
	 *            被除数值
	 * @param decimalDlaces
	 *            小数点位，比如"0.00"为保留两个小数点
	 * @return
	 */
	public static String decimals(int value1,int value2,String decimalDlaces){
		DecimalFormat df = new DecimalFormat(decimalDlaces);
		return df.format(value1/(float)value2);
	}

  /**
   * 随机数字字母组合
   *
   */
  public static String getItemID( int n )
  {
    String val = "";
    Random random = new Random();
    for ( int i = 0; i < n; i++ )
    {
      String str = random.nextInt( 2 ) % 2 == 0 ? "num" : "char";
      if ( "char".equalsIgnoreCase( str ) )
      { // 产生字母
        int nextInt = random.nextInt( 2 ) % 2 == 0 ? 65 : 97;
        // System.out.println(nextInt + "!!!!"); 1,0,1,1,1,0,0
        val += (char) ( nextInt + random.nextInt( 26 ) );
      }
      else if ( "num".equalsIgnoreCase( str ) )
      { // 产生数字
        val += String.valueOf( random.nextInt( 10 ) );
      }
    }

    return val.toUpperCase();
  }


}
